package com.tc.itfarm.commons.web.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

@Service("commonInvocationSecurityMetadataSource")
public class CommonInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

	private static Map<String, Collection<ConfigAttribute>> resourceMap = null;
	
	private PathMatcher pathMatcher = new AntPathMatcher();
	
	public CommonInvocationSecurityMetadataSource() {
		resourceMap = new HashMap<String, Collection<ConfigAttribute>>();
		Collection<ConfigAttribute> attributes = new ArrayList<ConfigAttribute>();
		ConfigAttribute ca = new SecurityConfig("ROLE_USER");
		attributes.add(ca);
		resourceMap.put("/admin/*", attributes);
		resourceMap.put("/admin*", attributes);
	}

	public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
		String url = ((FilterInvocation)object).getRequestUrl();
		Iterator<String> it = resourceMap.keySet().iterator();
		while(it.hasNext()){
			String resUrl = it.next();
			if(this.isMathed(url, resUrl)){
				return resourceMap.get(resUrl);
			}
		}
		return null;
	}

	private boolean isMathed(String url, String resUrl){
		if("/**".equals(resUrl) || "**".equals(resUrl)){
			return true;
		}
		return pathMatcher.match(resUrl, url);
	}
	
	public Collection<ConfigAttribute> getAllConfigAttributes() {
		return null;
	}

	public boolean supports(Class<?> clazz) {
		return true;
	}

}
